package com.starblink.search.result.ui

import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import androidx.viewpager.widget.ViewPager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.starblink.android.basic.base.fragment.BaseTVMFragment
import com.starblink.android.basic.bean.search.SearchResultPageArgs
import com.starblink.android.basic.ext.bindFragment
import com.starblink.android.basic.ext.bindSimpleTab
import com.starblink.android.basic.ext.color
import com.starblink.android.basic.ext.string
import com.starblink.android.basic.ext.visibleOrGone
import com.starblink.android.basic.extension.dp2px
import com.starblink.android.basic.sensorsdata.room.entity.SkAntEntity
import com.starblink.android.basic.sensorsdata.spm.GTrackerAssistUtils
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef
import com.starblink.android.basic.sensorsdata.spm.event.TrackEvent
import com.starblink.android.basic.sensorsdata.spm.impl.SpmTrackHandler
import com.starblink.basic.route.RoutePage
import com.starblink.search.R
import com.starblink.search.config.SearchConfig
import com.starblink.search.databinding.FragmentSearchResultBinding
import com.starblink.search.result.ui.fragment.brand.BrandResultFragment
import com.starblink.search.result.ui.fragment.goods.GoodsResultFragment
import com.starblink.search.result.ui.fragment.post.PostResultFragment
import com.starblink.search.result.ui.fragment.store.StoreResultFragment
import com.starblink.search.result.ui.fragment.user.UserResultFragment

/**
 * 搜索结果-主页
 */
@Route(path = RoutePage.Search.PAGE_SEARCH_RESULT)
internal class ResultMainFragment :
    BaseTVMFragment<FragmentSearchResultBinding, SearchResultVM>(), ViewPager.OnPageChangeListener {

    @JvmField
    @Autowired(name = RoutePage.Search.ARG_SEARCH_RESULT)
    var args: SearchResultPageArgs? = null


    private var goodsFragment: GoodsResultFragment? = null

    internal var textInputRequest: ((word: String?, curIndex: Int) -> Unit)? = null


    override fun getViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): FragmentSearchResultBinding = FragmentSearchResultBinding.inflate(layoutInflater)


    override fun initData() {
        args = arguments?.getParcelable(RoutePage.Search.ARG_SEARCH_RESULT)
        viewModel.keyword = args?.keyword
        viewModel.composeWords = args?.composeWords
    }

    override fun initView(view: View) {
        super.initView(view)

        args?.let {
            if (it.composeWords.isNullOrEmpty()) {
                it.keyword?.takeIf { it.isNotEmpty() }?.run {
                    viewBinding.searchWord.keyword = this
                }
            } else {
                viewBinding.searchWord.composeWords = it.composeWords
                viewBinding.searchWord.composeWordClick = { index ->
                    val word = if (index > 0) {
                        val strB = StringBuilder()
                        it.composeWords?.forEachIndexed { i, s ->
                            if (i < index) {
                                if (strB.isNotEmpty()) {
                                    strB.append(" ")
                                }
                                strB.append(s)
                            }
                        }
                        strB.toString()
                    } else {
                        it.keyword
                    }
                    //popSelf()
                    textInputRequest?.invoke(word, viewBinding.viewPager.currentItem)
                }
            }
        }
        viewBinding.back.setOnClickListener {
            popSelf()
        }

        var tabs = resources.getStringArray(R.array.search_tabs).toList()
        when (args?.scene) {
            RoutePage.Search.SCENE.GOODS -> {
                tabs = arrayListOf(string(R.string.tab_goods_name))
                viewBinding.viewPager.bindFragment(
                    childFragmentManager,
                    pageTitles = tabs,
                    count = tabs.size
                ) {
                    goodsFragment = GoodsResultFragment.newInstance(
                        keyword = viewModel.wordForQuery,
                        searchWordSource = args?.searchWordSource,
                        scene = SearchConfig.SCENE_GOODS,
                        goodsRuleId = args?.goodsRuleId
                    )
                    goodsFragment!!
                }
            }

            RoutePage.Search.SCENE.STORES -> {
                tabs = arrayListOf(string(R.string.tab_store_name))
                viewBinding.viewPager.bindFragment(
                    childFragmentManager,
                    pageTitles = tabs,
                    count = tabs.size
                ) {
                    StoreResultFragment.newInstance(
                        queryWord = viewModel.wordForQuery,
                        searchScene = args?.scene?.value ?: 0
                    )
                }
            }

            RoutePage.Search.SCENE.BRANDS -> {
                tabs = arrayListOf(string(R.string.tab_brand_name))
                viewBinding.viewPager.bindFragment(
                    childFragmentManager,
                    pageTitles = tabs,
                    count = tabs.size
                ) {
                    BrandResultFragment.newInstance(
                        queryWord = viewModel.wordForQuery,
                        searchScene = args?.scene?.value ?: 0
                    )
                }
            }

            RoutePage.Search.SCENE.NORMAL -> {
                tabs = resources.getStringArray(R.array.search_tabs_normal).toList()
                viewBinding.viewPager.bindFragment(
                    childFragmentManager,
                    pageTitles = tabs,
                    count = tabs.size,
                    pageChangeListener = this
                ) {
                    when (it) {
                        0 -> {
                            goodsFragment = GoodsResultFragment.newInstance(
                                viewModel.wordForQuery,
                                searchWordSource = args?.searchWordSource,
                                goodsRuleId = args?.goodsRuleId
                            )
                            goodsFragment!!
                        }

                        1 -> {
                            BrandResultFragment.newInstance(viewModel.wordForQuery)
                        }

                        2 -> {
                            StoreResultFragment.newInstance(viewModel.wordForQuery)
                        }

                        else -> GoodsResultFragment.newInstance(
                            viewModel.wordForQuery,
                            searchWordSource = args?.searchWordSource,
                            scene = SearchConfig.SCENE_ALL,
                            goodsRuleId = args?.goodsRuleId
                        )
                    }
                }
            }

            RoutePage.Search.SCENE.DISCOVER -> {
                tabs = resources.getStringArray(R.array.search_tabs_discover).toList()
                viewBinding.viewPager.bindFragment(
                    childFragmentManager,
                    pageTitles = tabs,
                    count = tabs.size
                ) {
                    when (it) {
                        0 -> {
                            PostResultFragment.newInstance(viewModel.wordForQuery)
                        }

                        1 -> {
                            UserResultFragment.newInstance(viewModel.wordForQuery)
                        }

                        else -> PostResultFragment.newInstance(viewModel.wordForQuery)
                    }
                }
            }

            else -> {
                viewBinding.viewPager.bindFragment(
                    childFragmentManager,
                    pageTitles = tabs,
                    count = tabs.size
                ) {
                    when (it) {
                        0 -> {
                            goodsFragment = GoodsResultFragment.newInstance(
                                viewModel.wordForQuery,
                                searchWordSource = args?.searchWordSource,
                                scene = SearchConfig.SCENE_ALL,
                                goodsRuleId = args?.goodsRuleId
                            )
                            goodsFragment!!
                        }

                        1 -> {
                            BrandResultFragment.newInstance(viewModel.wordForQuery)
                        }

                        2 -> {
                            StoreResultFragment.newInstance(viewModel.wordForQuery)
                        }

                        3 -> {
                            PostResultFragment.newInstance(viewModel.wordForQuery)
                        }

                        4 -> {
                            UserResultFragment.newInstance(viewModel.wordForQuery)
                        }

                        else -> {
                            GoodsResultFragment.newInstance(
                                viewModel.wordForQuery,
                                searchWordSource = args?.searchWordSource,
                                goodsRuleId = args?.goodsRuleId
                            )
                        }
                    }
                }
            }
        }
        viewBinding.tabs.visibleOrGone(tabs.size > 1) {
            bindSimpleTab(
                tabs,
                viewPager = viewBinding.viewPager,
                gap = 45.dp2px(),
                normalColor = color(com.starblink.basic.style.R.color.gu_text_tertiary),
                selectedColor = color(com.starblink.basic.style.R.color.gu_text_primary),
                textSize = 14f
            )
        }
        if ((args?.curTabIndex ?: 0) < (viewBinding.viewPager.adapter?.count ?: 0)) {
            viewBinding.viewPager.setCurrentItem(args?.curTabIndex ?: 0, false)
        }

        viewBinding.container.onDispatchEvent = { ev ->
            if (ev?.action == MotionEvent.ACTION_UP) {
                goodsFragment?.onParentViewTouch(ev)
            }
        }

        viewBinding.searchWord.setOnClickListener {
            //popSelf()
            textInputRequest?.invoke(
                viewBinding.searchWord.keyword,
                viewBinding.viewPager.currentItem
            )
        }
        viewBinding.searchWord.onCloseIconTap = {
            textInputRequest?.invoke(
                "",
                viewBinding.viewPager.currentItem
            )
        }
    }

    override fun startObserve() {

    }

    override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
    }

    override fun onPageSelected(position: Int) {
        if (args?.scene ?: 0 == RoutePage.Search.SCENE.NORMAL) {
            if (position == 1 || position == 2) {
                SpmTrackHandler.addSingleTrackData(
                    SkAntEntity(
                        event = TrackEvent.pageExposure.value,
                        spmCnt = GTrackerAssistUtils.fetchPageValue(if (position == 1) SpmPageDef.SearchBrandPage else SpmPageDef.SearchStoresPage),
                        params = mapOf(
                            "searchTerm" to viewModel.wordForQuery,
//                            "shadingWord" to "",
//                            "trending" to if (args?.searchWordSource == SearchConfig.SearchWordSourceConfig.O_TYPE_HOT ||
//                                args?.searchWordSource == SearchConfig.SearchWordSourceConfig.O_TYPE_SHADING
//                            ) viewModel.wordForQuery else "",
                            "searchType" to if (args?.searchWordSource == SearchConfig.SearchWordSourceConfig.O_TYPE_HOT) "trendingWord" else if (args?.searchWordSource == SearchConfig.SearchWordSourceConfig.O_TYPE_SHADING) "shadingWord" else "normal",
                        )
                    )
                )
            }
        }
    }

    override fun onPageScrollStateChanged(state: Int) {
    }


}